package plus.easydo.server.user.mp.controller;

import io.swagger.annotations.Api;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import plus.easydo.core.result.R;
import plus.easydo.server.user.mp.constant.UserConstants;
import plus.easydo.server.user.mp.entity.SysDept;
import plus.easydo.server.user.mp.service.ISysDeptService;
import plus.easydo.server.user.mp.vo.TreeSelect;
import plus.easydo.starter.mybatis.plus.base.MPBaseController;
import plus.easydo.starter.oauth.core.utils.Oauth2Utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@Api(tags = "部门信息")
@RestController
@RequestMapping("/dept")
public class SysDeptController extends MPBaseController {
    @Autowired
    private ISysDeptService deptService;

    @PreAuthorize("hasPermission('system:dept:list')")
    @GetMapping("/list")
    public R<List<SysDept>> list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return ok(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("hasPermission('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public R<List<SysDept>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("hasPermission('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public R<SysDept> getInfo(@PathVariable Long deptId) {
        return ok(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public R<List<TreeSelect>> treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return ok(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public Map<String, Object> roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Map<String, Object> map = new HashMap<>(4);
        map.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        map.put("depts", deptService.buildDeptTreeSelect(depts));
        return map;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("hasPermission('system:dept:add')")
    @PostMapping
    public R<Object> add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(Oauth2Utils.getUserName());
        return opResult(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("hasPermission('system:dept:edit')")
    @PutMapping
    public R<Object> edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return fail("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(Oauth2Utils.getUserName());
        return opResult(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("hasPermission('system:dept:remove')")
    @DeleteMapping("/{deptId}")
    public R<Object> remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return fail("部门存在用户,不允许删除");
        }
        return opResult(deptService.deleteDeptById(deptId));
    }
}
